package com.CST.service.impl.cb;

import com.CST.common.api.Response;
import com.CST.common.constant.Constants;
import com.CST.dto.cb.BdPerformanceDTO;
import com.CST.entity.cb.BdDepartment;
import com.CST.entity.cb.BdPerformance;
import com.CST.mapper.dataplatform.BdDepartmentMapper;
import com.CST.mapper.dataplatform.BdPerformanceMapper;
import com.CST.service.cb.IBdPerformanceService;
import com.CST.util.HttpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author qtx
 * @since 2023-05-16
 */
@Service
public class IBdPerformanceServiceImpl extends ServiceImpl<BdPerformanceMapper, BdPerformance> implements IBdPerformanceService {
@Autowired
private    BdPerformanceMapper   bdPerformanceMapper;
    @Autowired
    private BdDepartmentMapper bdDepartmentMapper;
    @Override
    public Response addPerformance(BdPerformance entity) {
        try {
            Date currDate = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:hh:ss");
            entity.setCreatedOn(sdf.format(currDate));
            entity.setUpdatedOn(sdf.format(currDate));
            String userName = HttpUtil.getRequestHeaderInfo(Constants.USER_NAME);
            userName = userName == null || userName.isEmpty() ? "System" : userName;
            entity.setCreatedBy(userName);
            entity.setUpdatedBy(userName);
           baseMapper.insert(entity);
        } catch (Exception ex) {
            return Response.error(String.join(":", "添加失败:", ex.getMessage()));
        }
        return Response.success("添加成功");
    }

    @Override
    public Response batchDeletePerformance(List<Integer> ids) {

        try {
            baseMapper.deleteBatchIds(ids);
        }
        catch (Exception ex)
        {
            return Response.error("删除失败");
        }
        return Response.success("删除成功");
    }

    @Override
    public Response modifyPerformance(BdPerformance entity) {
        if (entity.getId() == 0) {
            return Response.error("主键不能为空");
        }
        try {
            Date currDate = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:hh:ss");
            entity.setCreatedOn(sdf.format(currDate));
            entity.setUpdatedOn(sdf.format(currDate));
            String userName = HttpUtil.getRequestHeaderInfo(Constants.USER_NAME);
            userName = userName == null || userName.isEmpty() ? "System" : userName;
            entity.setCreatedBy(userName);
            entity.setUpdatedBy(userName);
            baseMapper.updateById(entity);
        } catch (Exception ex) {
            return Response.error(String.join(":", "修改失败", ex.getMessage()));
        }
        return Response.success("修改成功");
    }

    @Override
    public IPage<BdPerformance> getBdPerformance(BdPerformanceDTO  bdPerformanceDTO) {
        LambdaQueryWrapper<BdPerformance> lambdaQueryWrapper = new LambdaQueryWrapper();
        Page<BdPerformance> objectPage = new Page<>(bdPerformanceDTO.getPageNum(),bdPerformanceDTO.getPageSize());
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(bdPerformanceDTO.getDeptCode()),BdPerformance::getDeptCode,bdPerformanceDTO.getDeptCode())
                .like(StringUtils.isNotBlank(bdPerformanceDTO.getDeptName()),BdPerformance::getDeptName,bdPerformanceDTO.getDeptName())
                .eq(StringUtils.isNotBlank(bdPerformanceDTO.getPDeptCode()),BdPerformance::getPDeptCode,bdPerformanceDTO.getPDeptCode())
                .like(StringUtils.isNotBlank(bdPerformanceDTO.getPDeptName()),BdPerformance::getPDeptName,bdPerformanceDTO.getPDeptName());

        return baseMapper.selectPage(objectPage,lambdaQueryWrapper);
    }

    @Override
    public List<BdDepartment> getDepartmentSourceWithPerformance() {
        List<BdDepartment> department = bdDepartmentMapper.getDepartment(null,null);
        List<BdDepartment> pDepartment = bdDepartmentMapper.getPDepartment(null,null);
        List<BdPerformance> bdPerformances = baseMapper.selectList(new QueryWrapper<BdPerformance>().orderByAsc("PDeptCode"));
        List<BdDepartment> bdDepartments = new ArrayList<>();
        Map<String, List<BdPerformance>> collect = bdPerformances.stream().collect(Collectors.groupingBy(BdPerformance::getPDeptCode));
        Map<String, List<BdPerformance>> result = new LinkedHashMap<>();
        collect.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEachOrdered(x -> result.put(x.getKey(), x.getValue()));

        for (String s : result.keySet()) {
            BdDepartment bdDepartment = new BdDepartment();
            BdDepartment bdDepartment1 = pDepartment.stream().filter(t -> t.getDeptCode().equals(s)).findFirst().orElse(null);
            BeanUtils.copyProperties(bdDepartment1,bdDepartment);
            bdDepartment.setIsParent(true);
            List<BdPerformance> bdPerformances1 = result.get(s);
            List<BdDepartment> bdDepartmentList= new ArrayList<>();
            for (BdPerformance bdPerformance : bdPerformances1) {
                BdDepartment bdDepartment2 = department.stream().filter(t -> t.getDeptCode().equals(bdPerformance.getDeptCode())).findFirst().orElse(null);
               if (bdDepartment2!=null ){
                bdDepartment2.setIsParent(false);
                   bdDepartmentList.add(bdDepartment2) ;}
//                bdDepartmentList.add(bdDepartment2) ;
            }
            bdDepartments.add(bdDepartment);
            bdDepartments.addAll(bdDepartmentList);
        }
        return bdDepartments;
    }

    @Override
    public List<BdDepartment> getDeptCodeBdDepartments() {
        return bdPerformanceMapper.getDeptCodeBdDepartments();
    }

}
